import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Vector;

/**
 * @author lys
 * 搜索页面
 */

public class Search {
    private static Search instance;

    public static Search getInstance() {
        if(instance == null) instance = new Search();
        return instance;
    }

    public JLayeredPane jLayeredPane = new JLayeredPane();

    private JLabel jLabel = new JLabel("图书查询");
    private JLabel jLabel2 = new JLabel("请选择查询方式：");

    private JTextField field = new JTextField(25);

    private Dimension dimension = new Dimension(220, 30);

    private JComboBox<String> box = new JComboBox<String>();

    private JButton button = new JButton("搜索");

    public DefaultTableModel model = new DefaultTableModel();

    private Font font = new Font("宋体", Font.BOLD, 60);
    private Font font1 = new Font("宋体", Font.BOLD, 25);
    private Font font2 = new Font("宋体", Font.BOLD, 20);

    private String s;
    private String book;
    private int id;

    private Search() {

        Icon i = new ImageIcon(Search.class.getResource("img/4.jpg"));
        JLabel Label = new JLabel(i);
        Label.setBounds(0, 0, 1200, 800);

        jLabel.setFont(font);
        jLabel.setBounds(485, 35, 800, 100);
        jLabel.setForeground(Color.white);

        jLabel2.setFont(font1);
        jLabel2.setBounds(180, 130, 250, 30);
        jLabel2.setForeground(Color.white);

        box.setSize(dimension);
        box.addItem("按照类别查找");
        box.addItem("按照书名查找");
        box.addItem("按照作者查找");
        box.addItem("按照书号查找");
        box.setFont(font2);
        box.setBounds(180, 170, 200, 40);
        box.setOpaque(false);

        // 文本框
        field.setFont(font2);
        field.setSize(dimension);
        field.setBackground(Color.cyan);
        field.setBounds(480, 173, 250, 35);
        field.setForeground(Color.white);
        field.setOpaque(false);

        // 按钮
        button.setFont(font1);
        button.setBounds(850, 170, 100, 40);
        button.setForeground(Color.white);
        button.setBackground(Color.white);
        button.setOpaque(false);

        // 表格
        model.addColumn("书号", new Vector<Integer>());
        model.addColumn("类别", new Vector<Integer>());
        model.addColumn("书名", new Vector<Integer>());
        model.addColumn("作者", new Vector<Integer>());
        model.addColumn("出版社", new Vector<Integer>());
        model.addColumn("状态", new Vector<Integer>());

        JTable jTable = new JTable(model);
        jTable.setOpaque(false);


        JScrollPane pane = new JScrollPane(jTable);
        pane.setBounds(180, 250, 780, 400);
        pane.setOpaque(false);

        jTable.setVisible(false);
        pane.setVisible(false);

//		for(int k = 0; k < 30; k++) {
//			model.addRow(new Vector<Integer>());
//		}
       // FindBook.allbook(model);

        JTableHeader head = jTable.getTableHeader();
        // 设置表头的大小
        head.setPreferredSize(new Dimension(head.getWidth(), 30));
        // 设置表头字体大小
        head.setFont(new Font("宋体", Font.BOLD, 20));
        // head.setForeground(Color.cyan);
        head.setBackground(Color.cyan);
        // 设置表格的行宽
        jTable.setRowHeight(30);
        // 设置表格行中字体大小
        jTable.setFont(new Font("宋体", Font.ROMAN_BASELINE, 17));

        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
        jTable.setDefaultRenderer(Object.class, renderer);

        jLayeredPane.add(jLabel, new Integer(100), 1);
        jLayeredPane.add(jLabel2, new Integer(100), 2);
        jLayeredPane.add(box, new Integer(100), 3);
        jLayeredPane.add(field, new Integer(100), 4);
        jLayeredPane.add(button, new Integer(100), 5);
        jLayeredPane.add(pane, new Integer(100), 6);
        jLayeredPane.add(Label, new Integer(0), 0);

//        DefaultTableModel model2 = (DefaultTableModel) jTable.getModel();
//        String[] column1 = { "初代火影", "初代风影", "初代雷影", "初代水影", "初代土影", "初代光影"};
//        for(int k =0; k < 15; k ++){
//            model2.addRow(column1);
//        }

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jTable.setVisible(true);
                pane.setVisible(true);
                String keyword = field.getText();
                ArrayList<Book> books = returnSearch(type, keyword);
                if(books != null){
                    DefaultTableModel model2 = (DefaultTableModel) jTable.getModel();
                    model2.getDataVector().clear();
                    model2.fireTableDataChanged();
                    jTable.updateUI();
                    for(Book book: books){
                        String[] column = {String.valueOf(book.getBookId()), book.getType(), book.getBookName(), book.getWriter(), book.getPress(), "" };
                        if(book.isBorrowed()){
                            column[5] = "外借";
                        }
                        else{
                            column[5] = "在馆";
                        }
                        model2.addRow(column);
                    }
                }

            }
        });

        box.addItemListener(e -> {
            // TODO Auto-generated method stub
                if(e.getStateChange()==ItemEvent.SELECTED) {
                    s=(String)e.getItem();
                    if(s.equals("按照类别查找")){
                        type = 1;
                    }
                    else if(s.equals("按照书名查找")){
                        type = 2;
                    }
                    else if(s.equals("按照作者查找")){
                        type = 3;
                    }
                    else{
                        type = 4;
                    }
                }
        });

        button.setFocusPainted(false);
    }

    /**
     * 根据不同搜索方式搜索并返回搜索结果
     * @author zj
     * @return ArrayList<Book>
     */
    private int type = 1;
    public static ArrayList<Book> returnSearch(int type, String keyword){
        ArrayList<Book> books = new ArrayList<>();
        ResultSet rs;
        PreparedStatement preSql;
        String sql;
        Connection con = DatabaseConnection.getInstance().getCon();
        int flag = 0;
        if(type == 5){
            sql = "select * from book where bookid = ?";
            try{
                preSql = con.prepareStatement(sql);
                preSql.setString(1, keyword);
                rs = preSql.executeQuery();
                if(!rs.next()){
                    JOptionPane.showMessageDialog(null, "数据库中没有该书");
                    return null;
                }
                rs.previous();
                while(rs.next()){
                    int bookId = rs.getInt("bookid");
                    String bookName = rs.getString("bookname");
                    String press = rs.getString("press");
                    String theType = rs.getString("type");
                    String writer = rs.getString("writer");
                    Boolean isBorrowed = rs.getBoolean("isborrowed");
                    Book book = new Book(bookId, bookName, press, theType, writer, isBorrowed);
                    books.add(book);
                }
            }
            catch (Exception e){
                System.out.println(e);
            }
            return books;
        }
        if(keyword.length() == 0){
            try{
                sql = "select * from book";
                preSql = con.prepareStatement(sql);
                rs = preSql.executeQuery();
                while(rs.next()){
                    int bookId = rs.getInt("bookid");
                    String bookName = rs.getString("bookname");
                    String press = rs.getString("press");
                    String theType = rs.getString("type");
                    String writer = rs.getString("writer");
                    Boolean isBorrowed = rs.getBoolean("isborrowed");
                    Book book = new Book(bookId, bookName, press, theType, writer, isBorrowed);
                    books.add(book);
                }
            }catch(Exception e){
                System.out.println(e);
            }
            return books;
        }
        if(type == 1){
            try{
                sql = "select * from typelist where type like ?";
                preSql = con.prepareStatement(sql);
                preSql.setString(1, '%'+keyword+'%');
                rs = preSql.executeQuery();
                if(!rs.next()){
                    //此处应提供错误信息，暂时用sout替代
                    JOptionPane.showMessageDialog(null, "数据库中没有该类别");
                    return null;
                }
            }
            catch (Exception e){
                System.out.println(e);
            }
            sql = "select * from book where type like ?";
        }
        else if(type == 2){
            sql = "select * from book where bookname like ?";
        }
        else if(type == 3){
            sql = "select * from book where writer like ?";
        }
        else{
            sql = "select * from book where bookId = ?";
            flag = 1;
        }
        try{
            preSql = con.prepareStatement(sql);
            if(flag == 0) preSql.setString(1, '%'+keyword+'%');
            else preSql.setString(1, keyword);
            rs = preSql.executeQuery();
            if(!rs.next()){
                JOptionPane.showMessageDialog(null, "数据库中没有该书");
                return null;
            }
            rs.previous();
            while(rs.next()){
                int bookId = rs.getInt("bookid");
                String bookName = rs.getString("bookname");
                String press = rs.getString("press");
                String theType = rs.getString("type");
                String writer = rs.getString("writer");
                Boolean isBorrowed = rs.getBoolean("isborrowed");
                Book book = new Book(bookId, bookName, press, theType, writer, isBorrowed);
                books.add(book);
            }
        }
        catch (Exception e){
            System.out.println(e);
        }
        return books;
    }
    public static void removeInstance(){
        instance = null;
    }
}
